package com.jinsp.skinlib;

import android.app.Activity;
import android.app.Application;
import android.content.res.AssetManager;
import android.text.TextUtils;
import android.util.Log;

import java.io.IOException;
import java.util.Map;

/**
 * Created by luoshuai on 10/27/21
 * <p>
 * 皮肤库初始化
 */
public class SkinLibrary {

    /**
     * 初始化换肤框架
     *
     * @param application application实例
     */
    public static void init(Application application) {
        //注册生命周期监听
        application.registerActivityLifecycleCallbacks(new SkinActivityLifecycleCallback());
        //初始化resource
        ResourceManager.getInstance().init(application);
        //加载上一次配置的皮肤包
        SharedPreferencesUtils.init(application);
        String skinFilePath = SharedPreferencesUtils.getStringValue(ResourceManager.getInstance().SKIN_FILE_PATH, null);
        if (!TextUtils.isEmpty(skinFilePath)) {
            ResourceManager.getInstance().loadSkinResource(skinFilePath);
        }
    }

    /**
     * 更换资源
     *
     * @param activity     当前触发的activity
     * @param skinFilePath 皮肤路径
     */
    public static void changeResource(Activity activity, String skinFilePath) {
        //防止重复加载
        String currentUsingFilePath = SharedPreferencesUtils.getStringValue(ResourceManager.getInstance().SKIN_FILE_PATH, null);
        if (TextUtils.equals(currentUsingFilePath, skinFilePath)) {
            return;
        }
        long start = System.currentTimeMillis();
        Map<Activity, ActivityViewManager> activityViewManagerMap = SkinActivityLifecycleCallback.activityViewManagerMap;
        if (activityViewManagerMap.size() > 0) {
            ActivityViewManager activityViewManager = activityViewManagerMap.get(activity);
            if (activityViewManager != null) {
                activityViewManager.changeSkinResource(skinFilePath);
            }
        }
        Log.d(SkinLibrary.class.getCanonicalName(), "动态更换资源总耗时: " +
                (System.currentTimeMillis() - start) + "ms");
    }
}
